package jjn.round1;

/**
 * @author Jjn
 * @since 2022/8/10 22:21
 */
public class LeetCode443_CompressCharacters {

    public int compress(char[] chars) {
        int length = chars.length;
        if (length <= 1) {
            return length;
        }
        int count = 1;
        int write = 0;
        for (int i = 0; i < length; i++) {
            char now = chars[i];
            char next = i == length - 1 ? ' ' : chars[i + 1];
            if (now != next) {
                chars[write] = now;
                write++;
                if (count == 1) {
                    continue;
                }
                int len = Integer.toString(count).length();
                for (int j = (int) Math.pow(10, len - 1); j > 0; count %= j, j /= 10, write++) {
                    chars[write] = (char) (count / j + 48);
                }
                count = 1;
            } else {
                count++;
            }
        }
        return write;
    }
}
